<template>
    <div class="wrapper">
        <t-card>
            <t-row class="table-header">
                <t-space>
                    <t-input v-model="searchKey" placeholder="请输入搜索的姓名" size="medium"></t-input>
                    <t-button theme="primary" size="medium" @click="handleSearch">搜索</t-button>
                </t-space>
            </t-row>
            <t-table :row-key="rowKey" :data="userListData" :columns="columns" :size="size" :bordered="bordered"
                :stripe="stripe" :resizable="resizable" :loading="loading" :pagination="pagination"
                @page-change="rehandlePageChange" class="table-content">
                <template #options="{ row }">
                    <t-space>
                        <t-button theme="default" size="small" @click="showEditDialog(row)">编辑</t-button>
                    </t-space>
                </template>
            </t-table>
        </t-card>
        <t-dialog :visible="visibleEdit" header="编辑用户信息" :footer="false" width="500px" @close="visibleEditClose">
            <t-form ref="editFormRef" :data="editForm" :rules="editRules" :label-width="80" class="add-form"
                @submit="handleEditConfirm">
                <t-form-item label="姓名" name="name">
                    <t-input v-model="editForm.name" placeholder="请输入姓名" size="medium"></t-input>
                </t-form-item>
                <t-form-item label="性别" name="gender">
                    <t-select v-model="editForm.gender" placeholder="请选择性别" size="medium">
                        <t-option value="男">男</t-option>
                        <t-option value="女">女</t-option>
                    </t-select>
                </t-form-item>
                <t-form-item label="电话" name="phone">
                    <t-input v-model="editForm.phone" placeholder="请输入电话" size="medium"></t-input>
                </t-form-item>
                <t-form-item label="出生日期" name="birthday">
                    <t-date-picker
                        v-model="editForm.birthday"
                        mode="date"
                        format="YYYY-MM-DD"
                        placeholder="请选择出生日期"
                        size="medium"
                    />
                </t-form-item>
                <t-form-item label="地址" name="address">
                    <t-input v-model="editForm.address" placeholder="请输入地址" size="medium"></t-input>
                </t-form-item>
                <t-form-item>
                    <t-button type="submit" theme="primary" block>确定</t-button>
                </t-form-item>
            </t-form>
        </t-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import type { UserInfoList, UserInfoEditForm, SubmitParams } from '@/types/interface';
import { getUserInfo, editUserInfo } from '@/api/user';
import { useUserStore } from '@/store';

// id
const userStore = useUserStore();
const uid = userStore.id;

// 搜索框
const searchKey = ref('');


// 表格属性
const rowKey = ref('id');
const userListData = ref<UserInfoList[]>([]);
const size = ref('medium');
const bordered = ref(true);
const stripe = ref(true);
const resizable = ref(true);
const loading = ref(false);
const pagination = ref({
    defaultCurrent: 1,
    defaultPageSize: 10,
    total: 0,
    current: 1,
    pageSize: 10,
    pageSizeOptions: [2, 5, 10],
});

// 处理分页变化
const rehandlePageChange = async (curr: any, pageInfo: unknown) => {
    pagination.value.current = curr.current;
    pagination.value.pageSize = curr.pageSize;
    await getUserInfoListData();
};

// 表格列配置
const columns = ref([
    {
        title: '邮箱',
        colKey: 'email',
        align: 'center',
        width: 150,
    },
    {
        title: '姓名',
        colKey: 'name',
        align: 'center',
        width: 90,
    },
    {
        title: '性别',
        colKey: 'gender',
        align: 'center',
        width: 70,
    },
    {
        title: '电话',
        colKey: 'phone',
        align: 'center',
        width: 125,
    },
    {
        title: '出生年月',
        colKey: 'birthday',
        align: 'center',
        width: 115,
    },
    {
        title: '地址',
        colKey: 'address',
        align: 'center',
        width: 140,
    },
    {
        title: '更新时间',
        colKey: 'update_time',
        align: 'center',
        width: 120,
    },
    {
        title: '操作',
        colKey: 'options',
        align: 'center',
        width: 70,
    },
]);

// 编辑弹窗
const visibleEdit = ref(false);
const editFormRef = ref<UserInfoEditForm>({
    id: 0,
    name: '',
    gender: '',
    phone: '',
    birthday: '',
    address: '',
});
const editForm = ref<UserInfoEditForm>({
    id: 0,
    name: '',
    gender: '',
    phone: '',
    birthday: '',
    address: '',
});
const editRules = ref({
    phone: [
        {
            validator: (val: string) => {
                if (val && !/^1[3-9]\d{9}$/.test(val)) {
                    return { result: false, message: '请输入正确的11位手机号码' };
                }
                return { result: true };
            },
        },
    ],
    
});
const showEditDialog = (row: UserInfoList) => {
    visibleEdit.value = true;
    editForm.value.id = row.id;
    editForm.value.name = row.name;
    editForm.value.gender = row.gender;
    editForm.value.phone = row.phone;
    editForm.value.birthday = row.birthday;
    editForm.value.address = row.address;
};
const handleEditConfirm = async ({ validateResult, firstError }: SubmitParams) => {
    if (!validateResult) {
        console.error(firstError);
        return;
    }
    try {
        loading.value = true;
        const params = {
            id: editForm.value.id,
            name: editForm.value.name,
            gender: editForm.value.gender,
            phone: editForm.value.phone,
            birthday: editForm.value.birthday,
            address: editForm.value.address,
            uid: uid,
        }
        const res = await editUserInfo(params);
        if (res.errcode == 0) {
            loading.value = false;
            MessagePlugin.success(res.message, 1000);
            visibleEdit.value = false;
            getUserInfoListData();
        }
    } catch (error) {
        console.error('请求失败', error);
    }
};
const visibleEditClose = () => {
    visibleEdit.value = false;
};

// 搜索
const handleSearch = () => {
    pagination.value.current = 1;
    getUserInfoListData();
};

// 获取用户列表
const getUserInfoListData = async () => {
    const params = {
        page: pagination.value.current,
        pageSize: pagination.value.pageSize,
        searchKey: searchKey.value,
        uid: uid,
    };
    try {
        loading.value = true;
        const res = await getUserInfo(params);
        userListData.value = res.data.users;
        pagination.value.total = res.data.total;
        loading.value = false;
    } catch (error) {
        console.error('获取用户列表失败', error);
        // MessagePlugin.error('获取用户列表失败');
    } finally {
        loading.value = false;
    }
};

onMounted(() => {
    getUserInfoListData();
});
</script>

<style scoped>
.wrapper {
    padding: 20px;
}

.table-header {
    margin-top: 20px;
    margin-bottom: 20px;
}

.table-content {
    min-width: 900px;
}

.add-form {
    margin-top: 10px;
}
</style>
